# -*- coding:utf8 -*-
import json
import datetime
from django.core.urlresolvers import reverse
from django.http import HttpResponse, HttpResponseRedirect
import time
from wanbatvapp import settings
from wanbatvapp.http.decorators import require_params
from Crypto import Random
from Crypto.Cipher import PKCS1_v1_5
from Crypto.Signature import PKCS1_v1_5 as Signer
from Crypto.PublicKey import RSA
from Crypto.Hash import SHA
from wanbatvapp.settings import PRIVATE_ROOT
from wanbatvapp.settings import PAYMENT_HOST
from wanbatvapp.settings import MESSENGER_HOST

import os
import base64
import urllib
import urllib2

from wanbatvapp.http.whttp import \
    send_error_response_with_message, \
    send_error_response_on_exception, \
    send_ok_response_with_data, \
    send_ok_response_with_list, \
    send_response_with_result
from wanbatvapp.utils import decode_url_query

from wanpuzzle.models.common import Subject, Application, AppVersion, AppResVersion, AppResource

__author__ = 'Forcs'

RESOURCE_TYPE_APP_BACKGROUND = 1
RESOURCE_TYPE_WELCOME_BACKGROUND = 2
RESOURCE_TYPE_ORDER_WIN_BACKGROUND = 3


def get_app_version(request):
    version_name = None
    meta = request.META
    if "HTTP_ACCEPT" in meta:
        http_accept = meta["HTTP_ACCEPT"]
        accept_infos = http_accept.split(";")
        for accept_info_item in accept_infos:
            if accept_info_item.startswith("version"):
                version_name = accept_info_item.split("=")[1]
                break

    if not version_name and "HTTP_APP_VERSION" in meta:
        version_name = meta["HTTP_APP_VERSION"]

    version_code = 0
    if version_name:
        codes = version_name.split(".")
        codes.reverse()
        for index, code in enumerate(codes):
            c = int(code)
            version_code += c * (1000 ** index)

    return version_name, version_code


def get_subject(request, subject_code=None):

    version_name, version_code = get_app_version(request)
    # if version_code < 2000000:
    #     return send_error_response_with_message(message=u'改接口不支持此版本')
    # money = 0
    # body = request.GET
    # if "promocode" in body:
    #     coupon_code = body["promocode"]
    #     if coupon_code:
    #         coupon_item = Coupon.objects.get(code=coupon_code)
    #         money = coupon_item.money

    if not subject_code:
        return send_error_response_with_message(message='商品id无效')

    try:
        subject_model = Subject.objects.get(code=subject_code)
        subject = {
            "id": subject_model.id,
            "code": subject_model.code,
            "name": subject_model.name,
            "type": subject_model.type,
            "price": subject_model.price,
            "app": subject_model.application.token
        }
        # if money:
        #     subject["price"] = str(int(subject_model.price) - int(money))

        return send_ok_response_with_data(data=subject)
    except Exception as e:
        return send_error_response_on_exception(e)


def get_subjects(request, app_token=None):

    version_name, version_code = get_app_version(request)
    # if version_code < 2000000:
    #     return send_error_response_with_message(message=u'改接口不支持此版本')
    # money = 0
    # body = request.GET
    # if "promocode" in body:
    #     coupon_code = body["promocode"]
    #     if coupon_code:
    #         coupon_item = Coupon.objects.get(code=coupon_code)
    #         money = coupon_item.money
    try:
        sub_sq = Subject.objects.values("name", "code", "type", "price").filter(application__token=app_token)
        subject_list = []
        for subject in sub_sq:
            subject_type = subject["type"]
            subject_item = {
                "subject": subject["name"],
                "subjectId": subject["code"],
                "type": subject_type,
                "price": '%d' % (int(subject["price"]) / 100)
            }
            # if money:
            #     subject_item["price"] = str((int(subject["price"])-int(money)) / 100)
            if len(subject_list) < 2:
                subject_list.append(subject_item)

        return send_ok_response_with_list(subject_list)
    except Exception as e:
        return send_error_response_on_exception(e)


@require_params(["userid", ])
def check_pay(request, app_token=None):

    version_name, version_code = get_app_version(request)
    # if version_code < 2000000:
    #     return send_error_response_with_message(message=u'改接口不支持此版本')

    query = request.GET
    subject_code = None
    user_id = query["userid"]

    if 'subjectcode' in query:
        subject_code = query["subjectcode"]

    if user_id.index("_") > 0:
        # 安徽渠道限免，直接返回订购成功的标识，客户端不用显示订购弹窗
        flavor = user_id.split("_")[0]
        if flavor == 'anhui' or flavor == 'ah':
            return send_ok_response_with_data({
                "payCompleted": True,
                "expiration": 0,
                "reason": '限免',
            })

    url_list = {
        "stb": user_id,
        "appid":app_token
    }

    if subject_code:
        url_list["subjectcode"] = subject_code

    from wanbatvapp.settings import PAYMENT_HOST
    # 调用支付服务的鉴权接口

    req = urllib2.Request('http://%s/payment/auth' % PAYMENT_HOST,
                          urllib.urlencode(url_list))
    res = urllib2.urlopen(req)
    res_content = res.read()
    res.close()
    return send_response_with_result(res_content)


@require_params(["partner", "subjectid", "subject", "price", "provider", "stb", "flavor"], method="POST")
def request_order(request):

    version_name, version_code = get_app_version(request)
    # if version_code < 2000000:
    #     return send_error_response_with_message(message=u'改接口不支持此版本')

    body = request.POST
    partner = body["partner"]
    subject_id = body["subjectid"]
    subject_name = body["subject"]
    price = int(float(body["price"]) * 100)
    provider = body["provider"]

    gen_data = {
        "partner": partner,
        "subjectid": subject_id,
        "provider": provider,
        "stb": body["stb"],
        "flavor": body["flavor"],
        "subjecthost": request.get_host()
    }
    from wanbatvapp.settings import PAYMENT_HOST
    try:
        req = urllib2.Request('http://%s/order/gen' % PAYMENT_HOST, urllib.urlencode(gen_data))
        res = urllib2.urlopen(req)
        res_content = res.read()
        res.close()

        gen_result = json.loads(res_content, encoding='utf8')
        if gen_result["resultCode"] != 1:
            return send_error_response_with_message(message=gen_result["message"])
        order_no = gen_result["data"]["orderCode"]
    except Exception as e:
        return send_error_response_on_exception(e)

    if not order_no:
        return send_error_response_with_message(message='无法生成订单')

    if provider == 'alipay':
        order_template = 'partner=%s&subject_id=%s&subject=%s&price=%s&partner_notify_url=%s&partner_order_no=%s'
        notify_url = 'http://%s%s' % (request.get_host(), reverse(pay_notify, kwargs={"provider": provider}))
        order = order_template % (partner, subject_id, subject_name, price, notify_url, order_no)

        import os
        import base64
        from wanbatvapp.settings import PRIVATE_ROOT
        try:
            key = RSA.importKey(open(os.path.join(PRIVATE_ROOT, 'pem/wanba_rsa_private.pem')).read())
            cipher = Signer.new(key)
            sign_data = cipher.sign(SHA.new(order.encode(encoding='utf8')))
        except Exception as e:
            return send_error_response_on_exception(e)

        return send_ok_response_with_data(data={
            "sign": base64.b64encode(sign_data),
            "order": order,
            "orderOn": order_no
        })
    elif provider == 'openalipay' or provider == 'mipay':
        return send_ok_response_with_data(data={
            "order": order_no,
            "subject": subject_name,
            "price": body["price"],
            "sign": None
        })
    elif provider == 'hwpay' or provider == 'ahpay' or provider == "dangbeipay":
        return send_ok_response_with_data({
            "order": order_no,
            "subject": subject_name,
            "price": body["price"]
        })

    return send_error_response_with_message(message=u'不支持该产品')


def pay_result(request, provider=None):

    if provider.find("/"):
        arg = provider.split("/")
        provider = arg[0]

    order_status = ''
    msg = ''
    if provider == 'ahpay':
        query = request.GET
        keys = query.keys()

        import logging
        logger = logging.getLogger("wanba")
        logger.info("Pay result %s", query)

        order_status = 'cancel'
        if 'tradeInfo' in keys:
            order_status = 'success'
        if 'errorInfo' in keys:
            order_status = 'fail'
            err_info = json.loads(urllib.unquote(query["errorInfo"]), encoding='utf8')
            if 'respMsg' in err_info.keys():
                msg = err_info["respMsg"]

    return send_ok_response_with_data({
        "orderReturn": order_status
    }, message=msg if msg else '')


def _get_app_token_key(ordercode=None):
    try:
        if ordercode:
            url_data = {
                "ordercode": ordercode
            }
            req = urllib2.Request('http://%s/order/details/app_id' % PAYMENT_HOST, urllib.urlencode(url_data))
            res = urllib2.urlopen(req)
            content = res.read()
            print content
            res.close()

            res_content = json.loads(content)
            app_token = res_content["data"]["app_id"]
            app = Application.objects.get(token=app_token)
            return app.token+'_'+app.sign_key
        else:
            return send_response_with_result("订单号为空")
    except Exception as e:
        return send_error_response_on_exception(e)


def pay_notify(request, provider=None):
    # 支付获取私钥
    pri_key = RSA.importKey(open(os.path.join(PRIVATE_ROOT, 'pem/wanba_rsa_private.pem')).read())
    cipher = PKCS1_v1_5.new(pri_key)

    done_data = {
        "provider": provider
    }

    ext = None
    if provider.find("/") > 0:
        arg = provider.split("/")
        provider = arg[0]
        ext = arg[1]

    if provider == 'alipay':  # 阿里盒子
        import logging
        logger = logging.getLogger("wanba")
        logger.info('Notify from %s: %s' % (provider, json.dumps(request.POST)))
        # 回调的数据
        result_data = request.POST["data"]
        try:
            cipher_text = base64.b64decode(result_data)
            sentinel = Random.new().read(15 + SHA.digest_size)
            block_size = 128
            if len(cipher_text) == block_size:  # 如果长度为128，直接解密
                message = cipher.decrypt(cipher_text, sentinel)
                import logging
                logger = logging.getLogger("wanba")
                logger.info('Notify from %s' % message)
            else:  # 否则，将密文拆分成若干个长度为128的密文包进行解密，然后将解密得到的明文进行拼接得到最终的明文结果
                message = []
                offset = 0
                total_length = len(cipher_text)
                while offset < total_length:
                    msg_block = cipher.decrypt(cipher_text[offset:offset + block_size], sentinel)
                    message.append(msg_block)
                    offset += block_size
                message = "".join(message)
                import logging
                logger = logging.getLogger("wanba")
                logger.info('Notify from %s' % message)
        except Exception as e:
            return send_error_response_on_exception(e)

        if not message:
            return send_error_response_with_message(message="支付数据 %s 无效" % message)

        data_obj = json.loads(message, encoding='utf8')
        buyer_id = data_obj["buyer_logon_id"]
        done_data["ordercode"] = data_obj["partner_order_no"]
        done_data["tradeid"] = data_obj["alipay_trade_no"]
        done_data["buyer"] = buyer_id

    elif provider == 'openalipay':  # 支付宝

        import logging
        body = request.POST
        logger = logging.getLogger("wanba")
        logger.info('Notify from %s: %s' % (provider, json.dumps(request.POST)))

        order_code = body["out_trade_no"]
        done_data["ordercode"] = order_code
        done_data["tradeid"] = body["trade_no"]
        done_data["buyer"] = body["buyer_logon_id"]

        req = urllib2.Request('http://%s/order/details/stb_id' % PAYMENT_HOST,
                              urllib.urlencode({"ordercode": order_code}))
        res = urllib2.urlopen(req)
        content = res.read()
        res.close()

        result = json.loads(content)
        if result["resultCode"] == 1:
            stb_id = result["data"]["stb_id"]
            notify_data = dict()
            notify_data["api"] = "alipay.trade.precreate"
            notify_data["client"] = stb_id
            notify_data["data"] = json.dumps({
                "out_trade_no": order_code,
                "trade_no": body["trade_no"],
                "buyer_logon_id": body["buyer_logon_id"]
            })
            notify_data["app"] = _get_app_token_key(order_code)
            import logging
            logger = logging.getLogger("wanba")
            logger.info('Notify from %s' % json.dumps(notify_data))
            # notify_data["app"] = '9a64e88e7e2c9ec024799717bf4237c3_5e2ece5db0e0dd71a4e549ef7a28f9e7c0ed7306'
            req = urllib2.Request('http://%s/posthouse/notify/single' % MESSENGER_HOST, urllib.urlencode(notify_data))
            urllib2.urlopen(req)

    elif provider == 'mipay':  # 小米支付
        import logging
        logger = logging.getLogger("wanba")
        logger.info('Notify from %s: %s' % (provider, request.body))
        # print request.body
        body = json.loads(request.body, encoding='utf8')
        # body = request.body.replace("data=", "", 1)
        mipay_data = json.loads(base64.b64decode(body["data"]), encoding='utf8')
        # mipay_data = json.loads(base64.b64decode(body), encoding='utf8')
        done_data["ordercode"] = mipay_data["cust_order_id"]
        done_data["tradeid"] = mipay_data["pay_order_id"]
        done_data["buyer"] = "--"

    elif provider == 'hwpay':  # 华为计费
        import logging
        logger = logging.getLogger("wanba")
        logger.info('Notify from %s: %s' % (provider, request.GET))

        query = request.GET
        order_code = query["TradeNo"]
        trade_id = query["ConsumeStreamId"]

        done_data["ordercode"] = order_code
        done_data["tradeid"] = trade_id
        done_data["buyer"] = "--"

        req = urllib2.Request('http://%s/order/details/stb_id' % PAYMENT_HOST,
                              urllib.urlencode({"ordercode": order_code}))
        res = urllib2.urlopen(req)
        content = res.read()
        res.close()

        result = json.loads(content)
        if result["resultCode"] == 1:
            stb_id = result["data"]["stb_id"]

            notify_data = dict()
            notify_data["api"] = "hwpay.trade.done"
            notify_data["client"] = stb_id
            notify_data["data"] = json.dumps({
                "out_trade_no": order_code,
                "trade_no": trade_id,
                "buyer_logon_id": "",
            })
            notify_data["app"] = _get_app_token_key(order_code)
            # notify_data["app"] = '9a64e88e7e2c9ec024799717bf4237c3_5e2ece5db0e0dd71a4e549ef7a28f9e7c0ed7306'
            req = urllib2.Request('http://%s/posthouse/notify/single' % MESSENGER_HOST, urllib.urlencode(notify_data))
            urllib2.urlopen(req)

    elif provider == 'ahpay':  # 安徽计费
        body = request.POST if request.POST else json.loads(request.body, encoding='utf8')
        import logging
        logger = logging.getLogger("wanba")
        logger.info('Notify from %s: %s' % (provider, body))

        if "tradeInfo" not in body.keys():
            return send_error_response_with_message('缺少参数 tradeInfo')

        trade_info = urllib.unquote(body["tradeInfo"])
        if trade_info.find(' '):
            trade_info = trade_info.replace(' ', '+')

        try:
            import pyDes
            des_pri_key = '26f545c0d092463185acdd3e2c73fdda'
            data_decoded = base64.b64decode(trade_info.decode('utf-8'))
            des = pyDes.triple_des(des_pri_key[0: 24], mode=pyDes.CBC, padmode=pyDes.PAD_PKCS5, IV='01234567')
            trade_info = des.decrypt(data_decoded)
            trade_info_query = decode_url_query(trade_info, separator='|')
            trade_info_keys = trade_info_query.keys()
            if "orderId" in trade_info_keys:
                done_data["ordercode"] = trade_info_query["orderId"]
            if "autoRenew" in trade_info_keys:
                done_data["autorenew"] = trade_info_query["autoRenew"]
            if "beginDate" in trade_info_keys:
                done_data["begindate"] = trade_info_query["beginDate"]
            if "endDate" in trade_info_keys:
                done_data["enddate"] = trade_info_query["endDate"]
            done_data["buyer"] = ext
        except Exception as e:
            return HttpResponse("error %s " % str(e), content_type="text/plain;charset=utf-8")
    elif provider == 'dangbeipay':
        body = request.POST
        import logging
        logger = logging.getLogger("wanba")
        logger.info('Notify from %s: %s' % (provider, body))
        if 'datastr' not in body.keys():
            return send_error_response_with_message("缺少参数 datastr")

        datastr = urllib.unquote(body["datastr"])
        datastr = json.loads(datastr)
        Out_trade_no = datastr["Out_trade_no"]
        appkey = None
        app_token = None
        order_code = datastr["User_no"]
        try:
            if order_code:
                url_data = {
                    "ordercode": order_code
                }
                req = urllib2.Request('http://%s/order/details/app_id' % PAYMENT_HOST, urllib.urlencode(url_data))
                res = urllib2.urlopen(req)
                content = res.read()
                print content
                res.close()

                res_content = json.loads(content)
                app_token = res_content["data"]["app_id"]
        except Exception as e:
            return send_error_response_on_exception(e)
        if app_token == '9a64e88e7e2c9ec024799717bf4237c3':
            appkey = "99d6eb0bf7e22517b42cf6e1"
        if app_token == '5941dfdfd51a80cb795a505bbeeb250f':
            appkey = "6f63c0c417483cfff83f9f8f"
        Pay_user = datastr["Pay_user"]

        start = datastr["start"]
        import hashlib
        md5 = hashlib.md5()
        md5.update('{}{}{}{}'.format(Out_trade_no, appkey, Pay_user, "sign_85445221145"))
        version_token = md5.hexdigest()
        sign = body["sign"]
        if version_token == sign and start == "success":
        #if start == "success":
            done_data["ordercode"] = order_code
            done_data["budyer"] = Pay_user
            done_data["tradeid"] = Out_trade_no
        else:
            return send_error_response_with_message("参数校验错误")

    req = urllib2.Request("http://%s/order/done" % PAYMENT_HOST, urllib.urlencode(done_data))
    res = urllib2.urlopen(req)
    res.close()

    if provider == 'mipay':
        import time
        import datetime
        msg_id = mipay_data["msg_id"]
        mipay_return_data = {
            "msg_id": msg_id,
            "err_code": 200,
            "err_msg": "OK",
            "time": int(time.mktime(datetime.datetime.now().timetuple())) / 1000
        }
        cipher = Signer.new(pri_key)
        encoded_data = base64.b64encode(json.dumps(mipay_return_data, encoding='utf8'))
        sign_data = base64.b64encode(cipher.sign(SHA.new(encoded_data)))
        return HttpResponse(json.dumps({"data": encoded_data,
                                        "signature": sign_data}),
                            content_type="text/plain;charset=utf-8")

    elif provider == 'hwpay':
        return HttpResponse(json.dumps({"ErrorCode": 1,
                                        "ErrorDesc": 'success'}),
                            content_type="text/plain;charset=utf-8")

    return HttpResponse("success", content_type="text/plain;charset=utf-8")


@require_params(["code", "name", "appid", "token", "signkey", "package", "platform"], method="POST")
def sync_application(request):
    """
    同步应用数据
    :param request:
    :return:
    """
    body = request.POST
    code = body["code"]
    name = body["name"]
    app_id = body["appid"]
    package = body["package"]
    platform = body["platform"]
    token = body["token"]
    sign_key = body["signkey"]

    from wanpuzzle.models.common import Application
    try:
        app_model, created = Application.objects.get_or_create(token=token)
        app_model.name = name
        app_model.code = code
        app_model.app_id = app_id
        app_model.package = package
        app_model.platform = platform
        app_model.token = token
        app_model.sign_key = sign_key
        app_model.save()

        return send_ok_response_with_data(data={
            "syncApplication": True
        })
    except Exception as e:
        return send_error_response_on_exception(e)


@require_params(["code", "name", "type", "price", "apptoken"], method="POST")
def sync_subject(request):
    """
    同步商品包数据
    :param request:
    :return:
    """
    body = request.POST
    code = body["code"]
    name = body["name"]
    type = body["type"]
    price = body["price"]
    app_token = body["apptoken"]

    from wanpuzzle.models.common import Subject
    from wanpuzzle.models.common import Application
    try:
        app = Application.objects.get(token=app_token)

        sub_model, created = Subject.objects.get_or_create(code=code)
        sub_model.name = name
        sub_model.type = type
        sub_model.price = price
        sub_model.application = app
        sub_model.save()

        return send_ok_response_with_data(data={
            "syncSubject": True
        })
    except Exception as e:
        return send_error_response_on_exception(e)


@require_params(["versionname", "versioncode", "flavor", "apptoken",
                 "md5", "downloadurl", "token", "builddate"],
                method="POST")
def sync_version(request):
    """
    同步版本数据
    :param request:
    :return:
    """
    body = request.POST
    version_name = body["versionname"]
    version_code = body["versioncode"]
    flavor = body["flavor"]
    app_token = body["apptoken"]
    md5 = body["md5"]
    download_url = body["downloadurl"]
    token = body["token"]
    build_date = body["builddate"]

    try:
        app = Application.objects.get(token=app_token)

        ver_model, created = AppVersion.objects.get_or_create(token=token)
        ver_model.version_name = version_name
        ver_model.version_code = version_code
        ver_model.flavor = flavor
        ver_model.md5 = md5
        ver_model.dl_url = download_url
        ver_model.date_build = build_date
        ver_model.application = app
        ver_model.save()

        return send_ok_response_with_data(data={
            "syncVersion": True
        })
    except Exception as e:
        return send_error_response_on_exception(e)


def add_app_version(request, app_token=None):
    try:
        application = Application.objects.get(token=app_token)
    except Exception as e:
        return send_error_response_on_exception(e)

    body = request.POST
    version_name = body["versionname"]
    version_code = body["versioncode"]
    build_type = body["buildtype"]
    flavor = body["flavor"]
    date_build = body["date"]
    force = int(body["force"])

    pkg_name = '%s.%s.%s.build%s.ver%s.%s.apk' % (
        application.app_id, build_type, flavor, date_build, version_name, version_code)

    import hashlib
    md5 = hashlib.md5()
    md5.update('app={}&vn={}&vc={}&d={}&f={}&bt={}'.format(
        app_token, version_name, version_code, date_build, flavor, build_type))
    version_token = md5.hexdigest()

    try:
        new_version, created = AppVersion.objects.get_or_create(token=version_token)
        new_version.version_name = version_name
        new_version.version_code = version_code
        new_version.flavor = flavor
        new_version.date_build = date_build
        new_version.application = application
        new_version.md5 = version_token
        new_version.dl_url = '/apk/%s/v%s/%s/%s' % (application.package, version_name.replace('.', '_'), flavor, pkg_name)
        new_version.is_force = force == 1
        new_version.save()

        return send_ok_response_with_data({
            "token": version_token,
            "md5": version_token
        })
    except Exception as e:
        return send_error_response_on_exception(e)


def check_app_version(request, app_token=None):
    try:
        application = Application.objects.get(token=app_token)
    except Exception as e:
        return send_error_response_on_exception(e)

    body = request.POST
    flavor = body["flavor"]
    version_code = body["versioncode"]

    try:
        last_version = AppVersion.objects.order_by("-id").filter(application=application, flavor=flavor).first()
        if int(last_version.version_code) > int(version_code):
            return send_ok_response_with_data({
                "neekUpdate": True,
                "md5": last_version.md5,
                "token": last_version.token,
                "url": last_version.dl_url,
                "isForce": last_version.is_force
            })
        else:
            return send_ok_response_with_data({
                "needUpdate": False,
                "md5": "",
                "token": "",
                "url": "",
                "isForce": False
            })
    except Exception as e:
        return send_error_response_on_exception(e)


def check_app_res_version(request, app_token=None):

    try:
        application = Application.objects.get(token=app_token)
    except Exception as e:
        return send_error_response_on_exception(e)

    body = request.POST
    # flavor = body["flavor"]
    # stb_id = body["stb"]
    version = body["version"]

    curr_version = None
    if version:
        try:
            curr_version = AppResVersion.objects.get(version=version)
        except Exception:
            pass

    res = {
        "needUpdate": False,
        "version": version if version else '',
        "appBackgrounds": [],
        "welcomeBackgrounds": [],
        "orderWindowBackgrounds": [],
    }

    if curr_version:
        try:
            last_version = AppResVersion.objects.last()
            if last_version.id == curr_version.id:
                return send_ok_response_with_data(res)
        except Exception as e:
            return send_error_response_on_exception(e)
        res_ver_qs = AppResVersion.objects.filter(publish_date__gt=curr_version.publish_date, application=application)
    else:
        res_ver_qs = AppResVersion.objects.filter(application=application)

    versions = list()
    if res_ver_qs.exists() and res_ver_qs.count():
        for res_ver in res_ver_qs:
            versions.append(res_ver)

    if not versions:
        return send_ok_response_with_data(res)

    try:
        resource_qs = AppResource.objects.filter(version__in=versions) if versions \
            else AppResource.objects.all()

        def resource_item(res_model):
            item = dict()
            item["name"] = res_model.name
            item["url"] = res_model.data
            item["beginTime"] = long(time.mktime(res_model.begin_time.timetuple()) * 1000)
            item["endTime"] = long(time.mktime(res_model.end_time.timetuple()) * 1000)
            item["token"] = res_model.token
            return item

        for resource in resource_qs:
            if resource.res_type == RESOURCE_TYPE_APP_BACKGROUND:
                res["appBackgrounds"].append(resource_item(resource))
            elif resource.res_type == RESOURCE_TYPE_WELCOME_BACKGROUND:
                res["welcomeBackgrounds"].append(resource_item(resource))
            elif resource.res_type == RESOURCE_TYPE_ORDER_WIN_BACKGROUND:
                res["orderWindowBackgrounds"].append(resource_item(resource))
        res["version"] = versions[len(versions) - 1].version
        res["needUpdate"] = True
        return send_ok_response_with_data(res)

    except Exception as e:
        return send_error_response_on_exception(e)


def sync_app_res_version(request, app_token=None):

    body = request.POST
    version = body["version"]
    publish_date = body["publish"]

    try:
        application = Application.objects.get(token=app_token)
    except Exception as e:
        return send_error_response_on_exception(e)

    try:
        res_version, _ = AppResVersion.objects.get_or_create(version=version)
        res_version.publish_date = datetime.datetime.strptime(publish_date, '%Y-%m-%d %H:%M:%S')
        res_version.application = application
        res_version.save()
    except Exception as e:
        return send_error_response_on_exception(e)

    res_json_str = body["resources"]
    res_arr = json.loads(res_json_str, encoding='utf8')

    for resource in res_arr:
        res_model, _ = AppResource.objects.get_or_create(token=resource["token"])
        res_model.name = resource["name"]
        res_model.data = resource["data"]
        res_model.begin_time = datetime.datetime.strptime(resource["beginTime"], '%Y-%m-%d %H:%M:%S')
        res_model.end_time = datetime.datetime.strptime(resource["endTime"], '%Y-%m-%d %H:%M:%S')
        res_model.version = res_version
        res_model.res_type = resource["type"]
        res_model.save()

    return send_ok_response_with_data({
        "syncVersion": version,
        "publishDate": publish_date
    })


def get_app_resource(request, res_token=None):
    params = urllib.urlencode(request.GET)
    try:
        program = AppResource.objects.get(token=res_token)
        return HttpResponseRedirect("http://%s%s?%s" % (settings.WANBATV_CDN_URL, program.media, params))
    except Exception as e:
        return send_error_response_on_exception(e)


def get_config_track_host(request):
    return send_ok_response_with_data({
        "trackhost": "http://121.201.7.173:28060"
    })


def get_order_payed(request):
    body = request.POST
    stb_id = body["stbid"]
    app_id = body["appid"]
    payed_data = {
        "stb": stb_id,
        "appid": app_id,
    }
    req = urllib2.Request('http://%s/user/orders/done' % PAYMENT_HOST, urllib.urlencode(payed_data))
    res = urllib2.urlopen(req)
    res_content = res.read()
    res.close()
    return send_response_with_result(res_content)